﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Xml;

namespace RegexLib.Web.Models.Web
{
	/// <summary>
	/// 提供广告相关功能。
	/// </summary>
	public class RxAdsUtility
	{
		/// <summary>
		/// 按照配置名字获取广告代码。
		/// </summary>
		/// <param name="name">广告配置名称。</param>
		/// <returns></returns>
		public static string GetAdsCode(string name)
		{
			Dictionary<string, string> ads = GetAdsSettings();
			return ads[name];
		}

		const string AdsSettingsPath = "~/App_Data/Ads.xml";

		/// <summary>
		/// 获取~/App_Data/Ads.xml中的广告配置。
		/// </summary>
		/// <returns></returns>
		static Dictionary<string, string> GetAdsSettings()
		{
			// 1 尝试从缓存中获取
			Dictionary<string, string> codes = RxAppDataCache.Get<Dictionary<string, string>>(AdsSettingsPath);

			if (codes != null)
				return codes;

			// 2 从配置文件中读取
			codes = new Dictionary<string, string>();
			XmlDocument xdoc = new XmlDocument();
			xdoc.Load(HttpContext.Current.Server.MapPath(AdsSettingsPath));

			var nodes = xdoc.SelectNodes("/ads/ad");
			foreach (XmlNode n in nodes)
			{
				codes.Add(n.Attributes["name"].Value, n.InnerText);
			}

			// 3 放入缓存
			RxAppDataCache.Set<Dictionary<string, string>>(AdsSettingsPath, codes);
			return codes;
		}
	}
}
